/*


 */

package jas.rpc.http;

import jas.rpc.server.RpcListener;
import jas.rpc.*;
import jas.http.request.HttpRequest;
import jas.http.response.HttpResponse;
import jas.http.response.HttpResponseFactory;
import jas.http.response.ResponseCode;
import java.lang.reflect.InvocationTargetException;

/**
 *
 *
 */
public class RpcHttpResponseFactory implements HttpResponseFactory {
    
    private RpcHttpServerFormatter formatter;
    private RpcListener listener;
    
    public RpcHttpResponseFactory(RpcListener listener, RpcHttpServerFormatter formatter) {
        this.listener = listener;
        this.formatter = formatter;
    }
    
    public HttpResponse createResponse(HttpRequest request) {
        try {
            RpcRequest rpc = formatter.parseRequest(request);
            Object returnValue = listener.call(rpc);
            return formatter.writeResponse(returnValue);
        } catch (NoSuchMethodException ex) {
            return formatter.writeException(ex);
        } catch (InvocationTargetException ex) {
            return formatter.writeException(ex);
        } catch (NonRemoteMethodException ex) {
            return formatter.writeException(ex);
        } catch (IllegalArgumentException ex) {
            return HttpResponse.createStandardResponse(ResponseCode.BAD_REQUEST);
        }
    }
    
}
